/*
 * SQLComboBox.java
 *
 * Created on November 19, 2006, 5:39 PM
 */

package org.foment.joliage3.newt;

import java.awt.event.ItemEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.foment.joliage3.sql.Database;
import org.foment.joliage3.sql.Table;

/**
 *
 * @author  jaksa
 */
public class SQLComboBox extends javax.swing.JComboBox implements Table.TableListener {
    
    /** Creates new form BeanForm */
    public SQLComboBox() {
        initComponents();
        
        addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(ItemEvent e) {

              if (getSelectedIndex() != -1) {
                KeyValue k = (KeyValue) getSelectedItem();
                _currentKey = k.getKey();
              } else _currentKey = -1;
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {

    }// </editor-fold>//GEN-END:initComponents
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
    
    
     /**
     * Holds value of property tableName.
     */
    private String _tableName;
    private String _fieldName;
    private String _keyName;
    private String _query;
    private int _currentKey = 0;
    
    /**
     * Getter for property tableName.
     * @return Value of property tableName.
     */
    public String getTableName() {
        return _tableName;
     }

    
    public void setQuery(String query)
    {
        _query = query;
        readData();
    } 
    
     /**
     * Setter for property query.
     * @param query New value of property query.
     */
    public String getQuery()
    {
        return _query;
    }
    
    /**
     * Setter for property tableName.
     * @param tableName New value of property tableName.
     */
    public void setTableName(String tableName) {
        String oldTableName = _tableName;
        _tableName = tableName;
        readData();
        _propertyChangeSupport.firePropertyChange ("tableName", oldTableName, tableName);

    }

    /**
     * Getter for property keyName.
     * @return Value of property keyName.
     */
    public String getKeyName() {
        return _keyName;
    }

    /**
     * Setter for property keyName.
     * @param keyName New value of property keyName.
     */
    public void setKeyName(String keyName) {
        _keyName = keyName;
        readData();
    }

    /**
     * Getter for property fieldName.
     * @return Value of property fieldName.
     */
    public String getFieldName() {
        return _fieldName;
    }

    public String getSelectedValueName() {

        String value = "";
        if (getSelectedIndex() != -1) {

           KeyValue k = (KeyValue) getSelectedItem();
           value = k.getValue();
        }

        return value;
    }

    /**
     * Setter for property fieldName.
     * @param fieldName New value of property fieldName.
     */
    public void setFieldName(String fieldName) {
        _fieldName = fieldName;
        readData();
    }
    
    public void listenTables(String[] tables) {
      Table.removeListenerFromAll(this);
      for (String tableName: tables) {
       try {
          Database.getTable(tableName).addListener(this);
        } catch (SQLException ex) {
          ex.printStackTrace();
        }
      }
    }

    public void listenTables(String tables) {
      listenTables(tables.split(", *"));
    }

    private void readData() {
        String query = _query;
        if (_tableName != null && _keyName != null && _fieldName != null) {
          query = "SELECT " + _keyName + " AS keyName, " + _fieldName + " AS fieldName FROM " + _tableName + ";";
          listenTables(_tableName);
        }
        
        if (query == null) return ;
        
        try
        {
          removeAllItems();
          Connection conn = Database.getConnection();
          ResultSet rs   = conn.createStatement().executeQuery(query);

          while (rs.next())
            addItem(new KeyValue(rs.getInt("keyName"), 
              rs.getString("fieldName")));
          rs.close();
          
          if (getSelectedIndex() != -1) {
            KeyValue k = (KeyValue) getSelectedItem();
            _currentKey = k.getKey();
          } else _currentKey = -1;

          rs.close();
          conn.close();

        } catch (SQLException e)
        { e.printStackTrace(); }
        
    }
    
    /**
     * Getter for property value.
     * @return Value of property value.
     */
    public int getValue() {
        return _currentKey;
    }

    /**
     * Setter for property value.
     * @param value New value of property value.
     */
    public void setValue(int key) {
        int old_value = _currentKey;
        _currentKey = key;
        
        // display field for this key
        
        int itemNum = getItemCount();
        
        for (int i = 0; i < itemNum; i++)
        {
            KeyValue k = (KeyValue) getItemAt(i);

            if (k.getKey() == _currentKey)
            {
                setSelectedIndex(i);
                break;
            }
        }
        _propertyChangeSupport.firePropertyChange ("value", new Integer (old_value), new Integer (key));

    }

    public void tableRowDeleted(Table table, int row) {
        readData();
    }

    public void tableRowUpdated(Table table, int row) {
        readData();
    }

    public void tableRowInserted(Table table) {
        readData();
    }

    public void tableDataChanged(Table table) {
        readData();
    }
    
     /**
     * Utility field used by bound properties.
     */
    private java.beans.PropertyChangeSupport _propertyChangeSupport =  new java.beans.PropertyChangeSupport(this);
    
}
